package handlers

import (
	"log"
	"net/http"
	"path"

	"gitee.com/anxu/golang-web/src/models"
	"gitee.com/anxu/golang-web/src/repository"
)

type Thread struct {
	hander
}

func (this *Thread) Create(w http.ResponseWriter, r *http.Request) {

	user := this.user()
	if user == nil {
		this.redirect("login", http.StatusFound, w, r)
		return
	}

	if r.Method == http.MethodGet {
		this.render(w, nil, "layout", "auth.navbar", "new.thread")
		return
	}

	title := r.FormValue("topic")

	user.CreateThread(&models.Thread{Title: title})
	this.redirect("/", http.StatusFound, w, r)
}

func (this *Thread) View(w http.ResponseWriter, r *http.Request) {

	uuid := path.Base(r.URL.Path)
	thread := repository.Thread.FindByUuid(uuid)

	var files []string
	if user := this.user(); user == nil {
		log.Println(user)
		files = []string{"layout", "navbar", "thread"}
	} else {
		files = []string{"layout", "auth.navbar", "auth.thread"}
	}

	this.render(w, &thread, files...)
}
